document.addEventListener('DOMContentLoaded', () => {
  const blocks = document.querySelectorAll('.testimonials-block-feed');

  blocks.forEach(block => {
    const originalItems = Array.from(block.querySelectorAll('.testimonial'));
    if (originalItems.length <= 3) return;

    const parent = originalItems[0].parentElement;
    const wrapper = document.createElement('div');
    wrapper.classList.add('testimonials-slider-wrapper');

    const track = document.createElement('div');
    track.classList.add('testimonials-slider-track');

    const itemsToShow = 3;
    const totalItems = originalItems.length;

    // Клонируем первые itemsToShow и добавляем их в конец
    const allItems = [...originalItems];
    for (let i = 0; i < itemsToShow; i++) {
      const clone = originalItems[i].cloneNode(true);
      clone.classList.add('clone');
      allItems.push(clone);
    }

    allItems.forEach(item => track.appendChild(item));

    wrapper.appendChild(track);
    parent.appendChild(wrapper);

    const controls = document.createElement('div');
    controls.classList.add('slider-controls');

    const prev = document.createElement('button');
    prev.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none" viewBox="0 0 24 24">
        <path d="M15 18L9 12l6-6" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"></path>
      </svg>
    `;
    prev.classList.add('slider-prev');

    const next = document.createElement('button');
    next.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none" viewBox="0 0 24 24">
        <path d="M9 6l6 6-6 6" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"></path>
      </svg>
    `;
    next.classList.add('slider-next');

    controls.appendChild(prev);
    controls.appendChild(next);
    parent.appendChild(controls);

    let currentIndex = 0;
    let step = 1;
    let itemWidth;

    function isMobile() {
      return window.innerWidth <= 768;
    }

    function calculateStepAndWidth() {
      if (isMobile()) {
        step = 1;
        itemWidth = originalItems[0].offsetWidth + parseFloat(getComputedStyle(originalItems[0]).marginRight || 0);
      } else {
        step = itemsToShow;
        itemWidth = 100 / itemsToShow;
      }
    }

    function updatePosition(animated = true) {
      if (animated) {
        track.style.transition = 'transform 0.5s ease';
      } else {
        track.style.transition = 'none';
      }

      if (isMobile()) {
        const offset = -(currentIndex * itemWidth);
        track.style.transform = `translateX(${offset}px)`;
      } else {
        const offset = -(currentIndex * itemWidth);
        track.style.transform = `translateX(${offset}%)`;
      }
    }

    function goToNext() {
      const maxIndex = totalItems;

      currentIndex += step;
      updatePosition(true);

      if (currentIndex >= maxIndex) {
        setTimeout(() => {
          currentIndex = 0;
          updatePosition(false);
        }, 500);
      }
    }

    function goToPrev() {
      const maxIndex = totalItems;

      if (currentIndex === 0) {
        currentIndex = maxIndex;
        updatePosition(false);

        setTimeout(() => {
          currentIndex = maxIndex - step;
          updatePosition(true);
        }, 20);
      } else {
        currentIndex -= step;
        if (currentIndex < 0) currentIndex = 0; // защита от выхода за границы
        updatePosition(true);
      }
    }

    next.addEventListener('click', goToNext);
    prev.addEventListener('click', goToPrev);

    // swipe
    let startX = 0;
    track.addEventListener('touchstart', (e) => {
      startX = e.touches[0].clientX;
    });

    track.addEventListener('touchend', (e) => {
      const endX = e.changedTouches[0].clientX;
      const diff = endX - startX;

      if (Math.abs(diff) > 50) {
        if (diff > 0) {
          goToPrev();
        } else {
          goToNext();
        }
      }
    });

    window.addEventListener('resize', () => {
      calculateStepAndWidth();
      updatePosition(false);
    });

    calculateStepAndWidth();
    updatePosition();
  });
});